﻿#region The MIT License (MIT)
// The MIT License (MIT)
// Copyright (c) 2010 - 2013 Sovacode LLC
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Input;
using Sovacode.RubiksCube.Common.Command;
using Sovacode.RubiksCube.Common.Text;

namespace Sovacode.RubiksCube.Common.Managers.Command
{
    /// <summary>
    /// Command Manager
    /// </summary>
    internal sealed class CommandManager : Manager<ICommand>, ICommandManager
    {
        #region Register commands

        /// <summary>
        /// Register command by name
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="execute"><see cref="Action{T1,T2,T3,T4,T5,T6,T7,T8,T9}"/></param>
        public void RegisterCommand(string commandName, Action<object> execute)
        {
            RegisterCommand<object>(commandName, execute);
        }

        /// <summary>
        /// Register command by name
        /// </summary>
        /// <typeparam name="T">Parameter type</typeparam>
        /// <param name="commandName">Command name</param>
        /// <param name="execute"><see cref="Action{T1,T2,T3,T4,T5,T6,T7,T8,T9}"/></param>
        public void RegisterCommand<T>(string commandName, Action<T> execute)
        {
            RegisterCommand<T>(commandName, execute, param => true);
        }

        /// <summary>
        /// Register command by name
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="execute"><see cref="Action{T1,T2,T3,T4,T5,T6,T7,T8,T9}"/></param>
        /// <param name="canExecute"><see cref="Predicate{T}"/></param>
        public void RegisterCommand(string commandName, Action<object> execute, Predicate<object> canExecute)
        {
            RegisterCommand<object>(commandName, execute, canExecute);
        }

        /// <summary>
        /// Register command by name
        /// </summary>
        /// <typeparam name="T">Parameter type</typeparam>
        /// <param name="commandName">Command name</param>
        /// <param name="execute"><see cref="Action{T1,T2,T3,T4,T5,T6,T7,T8,T9}"/></param>
        /// <param name="canExecute"><see cref="Predicate{T}"/></param>
        public void RegisterCommand<T>(string commandName, Action<T> execute, Predicate<object> canExecute)
        {
            RegisterCommand(commandName, new RelayCommand<T>(execute, canExecute));
        }

        /// <summary>
        /// Register command by name
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="command">Command <see cref="ICommand"/></param>
        public void RegisterCommand(string commandName, ICommand command)
        {
            if (command == null)
            {
                command = GetCanNotRegisterErrorCommand(commandName);
            }

            if (Dictionary.ContainsKey(String.Intern(commandName)))
            {
                Dictionary[String.Intern(commandName)] = GetCanNotRegisterTwiceErrorCommand(commandName);

                return;
            }

            Trace.WriteLine(string.Format(CategorizedBy.TraceMessages.RegisterNewCommandTrace, commandName));

            Dictionary.Add(String.Intern(commandName), command);
        }

        #endregion

        #region Get Command

        /// <summary>
        /// Get command by name
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="force">False if needed null in case when command not found</param>
        /// <returns>Command <see cref="RelayCommand{T}"/></returns>
        public ICommand GetCommand(string commandName, bool force = true)
        {
            return Dictionary.ContainsKey(String.Intern(commandName))
                       ? Dictionary[String.Intern(commandName)]
                       : (force ? GetNotFoundErrorCommand(commandName) : null);
        }

        #endregion

        #region Error commands

        /// <summary>
        /// When command not found by name it will automatically registered new command with same name to show dialog with exception
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <returns>Command <see cref="ICommand"/></returns>
        private ICommand GetNotFoundErrorCommand(string commandName)
        {
            RegisterCommand(commandName,
                            new RelayCommand<string>(ShowCommandNotFound, param => true) {Type = CommandType.Error});

            return GetErrorCommand(commandName, commandName);
        }

        /// <summary>
        /// When command with empty action it will automatically registered new command with same name to show dialog with exception
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <returns>Command <see cref="ICommand"/></returns>
        private ICommand GetCanNotRegisterErrorCommand(string commandName)
        {
            RegisterCommand(commandName,
                            new RelayCommand<string>(ShowCommandAreEmpty, param => true) {Type = CommandType.Error});

            return GetErrorCommand(commandName, commandName);
        }

        /// <summary>
        /// When command tries to register twice it will automatically registered new command with same name to show dialog with exception
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <returns>Command <see cref="ICommand"/></returns>
        private ICommand GetCanNotRegisterTwiceErrorCommand(string commandName)
        {
            RegisterCommand(commandName,
                            new RelayCommand<string>(ShowCommandCannotBeRegisteredTwice, param => true)
                                {
                                    Type =
                                        CommandType
                                        .Error
                                });

            return GetErrorCommand(commandName, commandName);
        }

        /// <summary>
        /// System reserved
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="commandParameter">Error message</param>
        /// <returns>Command <see cref="ICommand"/></returns>
        private ICommand GetErrorCommand(string commandName, string commandParameter)
        {
            var errorCommand = (GetCommand(commandName, false) as RelayCommand<string>);

            if (errorCommand != null)
            {
                errorCommand.Parameter = commandParameter;
            }

            return errorCommand;
        }

        #endregion

        #region Error delegates

        /// <summary>
        /// System reserved
        /// </summary>
        /// <param name="commandName">Command name</param>
        private void ShowCommandNotFound(object commandName)
        {
            ShowError(string.Format(CategorizedBy.CommandManagerMessages.FailedCommandMessage, commandName));
        }

        /// <summary>
        /// System reserved
        /// </summary>
        /// <param name="commandName">Command name</param>
        private void ShowCommandAreEmpty(object commandName)
        {
            ShowError(string.Format(CategorizedBy.CommandManagerMessages.CommandIsEmptyMessage, commandName));
        }

        /// <summary>
        /// System reserved
        /// </summary>
        /// <param name="commandName">Command name</param>
        private void ShowCommandCannotBeRegisteredTwice(object commandName)
        {
            ShowError(string.Format(CategorizedBy.CommandManagerMessages.DuplicateCommandNameMessage, commandName));
        }

        #endregion

        #region IManager

        /// <summary>
        /// <see cref="IManager.InvalidProperties"/>
        /// </summary>
        public override IReadOnlyList<string> InvalidProperties
        {
            get
            {
                return (from keyValue in Dictionary
                        let typed = keyValue.Value as ICustomCommand
                        where typed != null && typed.Type == CommandType.Error
                        select keyValue.Key).ToList().AsReadOnly();
            }
        }

        /// <summary>
        /// <see cref="IManager.ValidProperties"/>
        /// </summary>
        public override IReadOnlyList<string> ValidProperties
        {
            get
            {
                return (from keyValue in Dictionary
                        let typed = keyValue.Value as ICustomCommand
                        where typed != null && typed.Type != CommandType.Error
                        select keyValue.Key).ToList().AsReadOnly();
            }
        }

        #endregion

    }
}